package cn.edu.zzu.nlp.utopiar.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;

import cn.edu.zzu.nlp.readTree.TreeParser;
import cn.edu.zzu.nlp.utopiar.editor.EditorTabbedPane;
import cn.edu.zzu.nlp.utopiar.editor.EditorToolBar;
import cn.edu.zzu.nlp.utopiar.editor.GraphEditor;
import cn.edu.zzu.nlp.utopiar.util.ValidCell;

public abstract class ActionGraph extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 * @param e
	 * @return Returns the graph for the given action event.
	 */
	public static final GraphEditor getEditor(ActionEvent e)
	{
		if (e.getSource() instanceof Component)
		{
			Component component = (Component) e.getSource();

			while (component != null
					&& !(component instanceof GraphEditor))
			{
				component = component.getParent();
			}

			return (GraphEditor) component;
		}

		return null;
	}
	
	public static String traverse(Object vertex, mxGraph graph)
	{
		String string = "";
		if (vertex != null)
		{
			int edgeCount = graph.getModel().getEdgeCount(vertex);
			string = (edgeCount!=1)?("("+graph.getLabel(vertex)+" "):graph.getLabel(vertex);
			List<Object> cells = new ArrayList<Object>();
			if (edgeCount > 0)
			{
				for (int i = 0; i < edgeCount; i++)
				{
					Object e1 = graph.getModel().getEdgeAt(vertex, i);
					boolean isSource = graph.getModel().getTerminal(e1, true) == vertex;

					if (isSource)
					{						
						Object next = graph.getModel().getTerminal(e1, !isSource);
						if(next!=null)
							cells.add(next);						
					}
				}
			}
	        for (int i = cells.size() - 1; i > 0; --i) {
	            boolean isSort=false;
	            for (int j = 0; j < i; ++j) {
	                if (graph.getCellBounds(cells.get(j+1)).getCenterX()< graph.getCellBounds(cells.get(j)).getCenterX()) {
	                    Object temp = cells.get(j);
	                    cells.set(j, cells.get(j+1));
	                    cells.set(j+1, temp);
	                    isSort=true;
	                }
	            }
	            if(!isSort)break;
	        }
			for (int i =0 ;i<cells.size();i++) {
				String temp;
				temp = traverse(cells.get(i) ,graph) ;
				string = string +  temp ;
			}
			if(edgeCount!=1)
			    string = string +  ")";
		}		
		return string;
	}
	
	public void refreshTree(GraphEditor editor, int count){
		mxGraphComponent graphComponent = GraphEditor.getGraphComponent();
		mxGraph graph = graphComponent.getGraph();
		mxGraph orGraph = EditorTabbedPane.getPATH().equalsIgnoreCase(EditorTabbedPane.getEnglishPath())?
				EditorTabbedPane.getZhGraph():EditorTabbedPane.getEngGraph();
		String orPath = EditorTabbedPane.getPATH().equalsIgnoreCase(EditorTabbedPane.getEnglishPath())?
				EditorTabbedPane.getChinesePath():EditorTabbedPane.getEnglishPath();
		mxGraphComponent orGraphComponent= EditorTabbedPane.getPATH().equalsIgnoreCase(EditorTabbedPane.getEnglishPath())?
				EditorTabbedPane.getZhGraphComponent():EditorTabbedPane.getEngGraphComponent();
		graph.selectAll();
		graph.removeCells();
		orGraph.selectAll();
		orGraph.removeCells();
		TreeParser.setCountleaf(1);
		TreeParser.setNow(count);
		
		List<String> list = TreeParser.getWord(count,TreeParser.selectData(orPath));
		TreeParser.getLeaf().clear();
		TreeParser.getSplitList().clear();
		TreeParser.creatTree(editor,orGraphComponent,list, 0);
		
		TreeParser.setCountleaf(1);
		List<String> list1 = TreeParser.getWord(TreeParser.getNow(),TreeParser.selectData(EditorTabbedPane.getPATH()));
		TreeParser.getLeaf().clear();
		TreeParser.getSplitList().clear();
		TreeParser.creatTree(editor, graphComponent, list1, 0);
		ValidCell.valid(editor);
		EditorToolBar.getCombobox().setSelectedIndex(0);
		EditorToolBar.getDescription().setText("   当前第"+(TreeParser.getNow()+1)+"条    ");
	}
	
	public static String getSaveStr(GraphEditor editor, mxGraph graph){
		String str="";
		Object cell = null;
		List<Object> list = graph.findTreeRoots(graph.getDefaultParent());
		if(list.size()>1){
			String str1 = "";
			for (int i =0;i<list.size();i++) {
				str1=str1+graph.getLabel(list.get(i))+"  ";
			}
			JOptionPane.showMessageDialog(editor, "现有"+list.size()+"个根节点："+str1);
			return null;
		}else {
			for (Object object : list) {
				cell = object;
			}
		}
		graph.selectCells(true, false);
		Object []objects = graph.getSelectionCells();	
		for (Object object : objects) {
			if(objects.length==1)
				break;
			int count = graph.getModel().getEdgeCount(object);				
			if(count<1){
				System.out.println(graph.getLabel(object));
				JOptionPane.showMessageDialog(editor, "结点\""+graph.getLabel(object)+"\"是孤立结点！");
				graph.clearSelection();
				return null;
			}
		}
		graph.clearSelection();
		str = traverse(cell, graph);
		String[] strings = str.split(" ");
		for (String string2 : strings) {
			if(!string2.contains(")(")&&string2.contains("(")&&!string2.startsWith("(")){
				JOptionPane.showMessageDialog(editor, "请核对叶子结点是否正确！","警告",JOptionPane.WARNING_MESSAGE);
				return null ;
			}
		}			
		str = "( " + str.replaceAll("\\)\\(", "\\) \\(") + " )";
		return str;
	}
}
